package logic

import (
	"context"
	"errors"
	"math/rand"
	"shuqi-novel/models/cache"
	"shuqi-novel/pkg"
	"strconv"
	"time"

	"shuqi-novel/shuqirpc/internal/svc"
	"shuqi-novel/shuqirpc/shuqirpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *shuqirpc.SendSmsRequest) (*shuqirpc.SendSmsResponse, error) {
	// 发送短信
	//实现1、短信验证码有效期3分钟，2、一分钟之内只允许发送一条信息，3、十分钟内限制发送三条信息

	result, _ := cache.RDB.Get(l.ctx, "count"+in.Account).Int()
	if result >= 1 {
		return nil, errors.New("一分钟之内只允许发送一条信息")
	}

	results, _ := cache.RDB.Get(l.ctx, "first"+in.Account).Int()
	if results >= 3 {
		return nil, errors.New("十分钟之内只允许发送三条信息")
	}

	code := rand.Intn(9000) + 1000
	sms, err := pkg.SendSms(in.Account, strconv.Itoa(code))
	if err != nil {
		return nil, errors.New(err.Error())
	}

	if sms.Code != 2 {
		return nil, errors.New(sms.Msg)
	}
	//短信验证码有效期三分钟
	cache.RDB.Set(l.ctx, "sendSms"+in.Account, code, time.Minute*3)
	//一分钟之内只能发送一条信息
	cache.RDB.Set(l.ctx, "count"+in.Account, 1, time.Minute*1)
	cache.RDB.Incr(l.ctx, "first"+in.Account)

	if results == 0 {
		cache.RDB.Expire(l.ctx, "first"+in.Account, time.Minute*10)
	}

	return &shuqirpc.SendSmsResponse{}, nil
}
